package com.example.cc.client.autoconfigure;

import com.example.cc.client.properties.RabbitMqProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(ConnectionFactory.class)
@EnableConfigurationProperties(RabbitMqProperties.class)
public class RabbitAutoConfiguration {

    private final RabbitMqProperties properties;

    public RabbitAutoConfiguration(RabbitMqProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean(ConnectionFactory.class)
    public ConnectionFactory rabbitConnectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(properties.getHost());
        connectionFactory.setVirtualHost(properties.getVirtualHost());
        connectionFactory.setUsername(properties.getUsername());
        connectionFactory.setPassword(properties.getPassword());
        connectionFactory.setPort(properties.getPort());
        return connectionFactory;
    }
}
